#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"

trigger-scheduler-docker-local-scheduler-docker-cleanup() {
  declare desc="scheduler-docker-local scheduler-docker-cleanup plugin trigger"
  declare trigger="scheduler-docker-cleanup"
  declare DOKKU_SCHEDULER="$1" APP="$2" FORCE_CLEANUP="$3"

  if [[ "$DOKKU_SCHEDULER" != "docker-local" ]]; then
    return
  fi

  if [[ -n "$APP" ]]; then
    # delete all non-running containers
    # shellcheck disable=SC2046
    "$DOCKER_BIN" container rm $("$DOCKER_BIN" container list --all --filter "status=exited" --filter "label=$DOKKU_CONTAINER_LABEL" --filter "label=com.dokku.app-name=$APP" --quiet) &>/dev/null || true

    # delete all dead containers
    # shellcheck disable=SC2046
    "$DOCKER_BIN" container rm $("$DOCKER_BIN" container list --all --filter "status=dead" --filter "label=$DOKKU_CONTAINER_LABEL" --filter "label=com.dokku.app-name=$APP" --quiet) &>/dev/null || true

    # delete danging images
    # shellcheck disable=SC2046
    "$DOCKER_BIN" image rm $("$DOCKER_BIN" image list --filter 'dangling=true' --filter "label=com.dokku.app-name=$APP" --quiet) &>/dev/null || true

    # delete unused images
    "$DOCKER_BIN" image prune --all --filter "label=com.dokku.app-name=$APP" --force &>/dev/null || true
  else
    # delete all non-running containers
    # shellcheck disable=SC2046
    "$DOCKER_BIN" container rm $("$DOCKER_BIN" container list --all --filter "status=exited" --filter "label=$DOKKU_CONTAINER_LABEL" --quiet) &>/dev/null || true

    # delete all dead containers
    # shellcheck disable=SC2046
    "$DOCKER_BIN" container rm $("$DOCKER_BIN" container list --all --filter "status=dead" --filter "label=$DOKKU_CONTAINER_LABEL" --quiet) &>/dev/null || true

    # delete danging images
    # shellcheck disable=SC2046
    "$DOCKER_BIN" image rm $("$DOCKER_BIN" image list --filter 'dangling=true' --quiet) &>/dev/null || true
  fi
}

trigger-scheduler-docker-local-scheduler-docker-cleanup "$@"
